package com.ruoyi.web.controller.projects;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.conditions.ProjectsConditions;
import com.ruoyi.system.domain.FileUpload;
import com.ruoyi.system.domain.ProjectsProgress;
import com.ruoyi.system.response.ProjectsInfo;
import com.ruoyi.system.response.ProjectsInfoExport;
import com.ruoyi.system.service.IFileUploadService;
import com.ruoyi.system.service.IProjectsProgressService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Projects;
import com.ruoyi.system.service.IProjectsService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 项目信息Controller
 *
 * @author tanshen
 * @date 2023-10-07
 */
@Controller
@RequestMapping("/projects/projects")
public class ProjectsController extends BaseController {
    private String prefix = "projects/projects";

    @Autowired
    private IProjectsService projectsService;

    @Autowired
    private IProjectsProgressService projectsProgressService;

    /**
     * 查询项目信息列表
     */
    @RequiresPermissions("projects:projects:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Projects projects) {
        ProjectsConditions projectsConditions = BeanUtils.copy(projects, ProjectsConditions.class);
        startPage(false);
        List<ProjectsInfo> list = projectsService.selectProjectsList(projectsConditions);
        List<Long> projectIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            projectIds = list.stream().map(Projects::getId).collect(Collectors.toList());
        }
        List<ProjectsProgress> progressList = projectsProgressService.selectProgress(projectIds);
        if (!CollectionUtils.isEmpty(progressList)) {
            Map<Long, List<ProjectsProgress>> map = progressList.stream().collect(Collectors.groupingBy(ProjectsProgress::getProjectId));
            for (ProjectsInfo projectsInfo : list) {
                List<ProjectsProgress> pList = map.get(projectsInfo.getId());
                if (CollectionUtils.isEmpty(pList)) {
                    continue;
                }
                Map<Integer, List<ProjectsProgress>> progressMap = pList.stream().collect(Collectors.groupingBy(ProjectsProgress::getType));
                projectsInfo.setLastProgress(getLastProjectsProgress(progressMap));
            }
        }
        Long count = projectsService.selectProjectsCount(projectsConditions);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(list);
        rspData.setTotal(count);
        return rspData;
    }

    private ProjectsProgress getLastProjectsProgress(Map<Integer, List<ProjectsProgress>> progressMap) {
        List<ProjectsProgress> list1 = progressMap.get(0);
        List<ProjectsProgress> list2 = progressMap.get(1);

        ProjectsProgress p0, p1, last = new ProjectsProgress();
        if (CollectionUtils.isNotEmpty(list1)) {
            p0 = list1.stream().sorted(Comparator.comparing(BaseEntity::getCreateTime)).reduce((a, b) -> b).orElse(null);
            last.setProgressContent(p0 != null ? p0.getProgressContent() : null);
        }
        if (CollectionUtils.isNotEmpty(list2)) {
            p1 = list2.stream().sorted(Comparator.comparing(BaseEntity::getCreateTime)).reduce((a, b) -> b).orElse(null);
            last.setTechnicalAgreementProgress(p1 != null ? p1.getProgressContent() : null);
        }
        return last;
    }

    @RequiresPermissions("projects:projects:view")
    @GetMapping("view")
    public String projectsView(ModelMap modelMap) {
        ProjectsConditions projectsConditions = new ProjectsConditions();
        projectsConditions.setIsView(true);
        List<ProjectsInfo> list = projectsService.selectProjectsList(projectsConditions);
        if (!CollectionUtils.isEmpty(list)) {
            Map<Integer, List<ProjectsInfo>> collect = list.stream().collect(Collectors.groupingBy(ProjectsInfo::getStatus));
            modelMap.put("projects", collect);
        }
        return prefix + "/projects-view";
    }

    @RequiresPermissions("projects:projects:listPage")
    @GetMapping()
    public String projects() {
        return prefix + "/projects-list";
    }

    /**
     * 导出项目信息列表
     */
    @RequiresPermissions("projects:projects:export")
    @Log(title = "项目信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Projects projects) {
        ProjectsConditions projectsConditions = BeanUtils.copy(projects, ProjectsConditions.class);
        List<ProjectsInfo> list = projectsService.selectProjectsList(projectsConditions);
        List<Long> projectIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            projectIds = list.stream().map(Projects::getId).collect(Collectors.toList());
        }

        List<ProjectsProgress> progressList = projectsProgressService.selectProgress(projectIds);
        if (!CollectionUtils.isEmpty(progressList)) {
            Map<Long, List<ProjectsProgress>> map = progressList.stream().collect(Collectors.groupingBy(ProjectsProgress::getProjectId));
            for (ProjectsInfo projectsInfo : list) {
                List<ProjectsProgress> pList = map.get(projectsInfo.getId());
                if (CollectionUtils.isEmpty(pList)) {
                    continue;
                }
                Map<Integer, List<ProjectsProgress>> progressMap = pList.stream().collect(Collectors.groupingBy(ProjectsProgress::getType));
                projectsInfo.setLastProgress(getLastProjectsProgress(progressMap));
            }
        }
        List<ProjectsInfoExport> exports = new ArrayList<>();
        for (ProjectsInfo projectsInfo : list) {
            ProjectsInfoExport export = new ProjectsInfoExport();
            BeanUtils.copyProperties(projectsInfo, export);

            ProjectsProgress lastProgress = projectsInfo.getLastProgress();
            if (Objects.nonNull(lastProgress)) {
                export.setProgressContent(lastProgress.getProgressContent());
                export.setTechnicalAgreementProgress(lastProgress.getTechnicalAgreementProgress());
            }
            SysUser owner = projectsInfo.getOwner();
            if (Objects.nonNull(owner)) {
                export.setOwner(owner.getUserName());
            }
            switch (projectsInfo.getStatus()) {
                case 0:
                    export.setStatus("筹备中");
                    break;
                case 1:
                    export.setStatus("未启动");
                    break;
                case 2:
                    export.setStatus("进行中");
                    break;
                default:
                    export.setStatus("已完成");
                    break;
            }

            List<SysUser> userList = projectsInfo.getUserList();
            if (CollectionUtils.isNotEmpty(userList)) {
                String users = userList.stream().map(SysUser::getUserName).collect(Collectors.joining(","));
                export.setTeamMembers(users);
            }
            exports.add(export);
        }
        ExcelUtil<ProjectsInfoExport> util = new ExcelUtil<>(ProjectsInfoExport.class);
        return util.exportExcel(exports, "项目信息数据");
    }

    /**
     * 新增项目信息
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存项目信息
     */
    @RequiresPermissions("projects:projects:add")
    @Log(title = "项目信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Projects projects) {
        return toAjax(projectsService.insertProjects(projects));
    }

    /**
     * 修改项目信息
     */
    @RequiresPermissions("projects:projects:edit")
    @GetMapping("/edit/{id}")  
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        ProjectsInfo projects = projectsService.selectProjectsById(id);
        mmap.put("projects", projects);
        return prefix + "/edit";
    }

    /**
     * 修改项目信息
     */
    @RequiresPermissions("projects:projects:detail")
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap) {
        ProjectsInfo projects = projectsService.selectProjectsById(id);
        projectsProgressService.selectProjectsProgressByProjectId(id, projects);
        mmap.put("projects", projects);
        return prefix + "/detail";
    }

    /**
     * 修改保存项目信息
     */
    @RequiresPermissions("projects:projects:edit")
    @Log(title = "项目信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Projects projects) {
        return toAjax(projectsService.updateProjects(projects));
    }

    /**
     * 删除项目信息
     */
    @RequiresPermissions("projects:projects:remove")
    @Log(title = "项目信息", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(projectsService.deleteProjectsByIds(ids));
    }
}
